package com.hqyj.bigdata_project.util;

import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

@Component
public class HiveUtil {

    //把本地数据文件导入到指定的表中。
    public static void importData(String path, String tableName) throws SQLException {
        String hql = "load data local inpath '" + path + "' into table " + tableName;
        PreparedStatement pstm = HiveConnection.getConnection().prepareStatement(hql);
        boolean flag = pstm.execute(hql);

        pstm.close();
    }

    //执行DML操作
    public static void execute(String hql) throws SQLException {
        PreparedStatement pstm = HiveConnection.getConnection().prepareStatement(hql);
        boolean flag = pstm.execute(hql);

        pstm.close();

    }

    //执行DQL操作
    public static ResultSet query(String hql) throws SQLException {
        try {
            //String sql = "select name,addr.province,addr.city,addr.street from t_person";
            PreparedStatement pstm = HiveConnection.getConnection().prepareStatement(hql);
            ResultSet rs = pstm.executeQuery(hql);

            /*
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取字段的个数
            int filedCount = rsmd.getColumnCount();
            StringBuilder sb = new StringBuilder();
            while (rs.next()) {
                for(int i=1;i<=filedCount;i++){
                    sb.append(rs.getString(i)+" ");
                }
                sb.append("\r\n");
            }
            System.out.println(sb);
            pstm.close();*/
            //rs.close();
            return rs;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /*
    public static void main(String[] args) {
        try{
            //HiveUtil.query("select name,addr.province,addr.city,addr.street from t_person");
            HiveUtil.query("select uid,username,password from users");
            //HiveUtil.execute("insert into t_person (name,addr) select \"小龙女\",named_struct(\"province\", \"浙江省\",\"city\",\"温州市\",\"street\",\"古墓\")");
            //HiveUtil.importData("/root/examples/users.txt","users");
            //HiveUtil.importData("d:/uploadFiles/users.txt","users");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }*/
}
